package com.macro.mall.portal.service.impl;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.service.CommentService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private PmsProductCommentMapper commentMapper;
    @Autowired
    private PmsProductCommentLabelCentreMapper centreMapper;
    @Autowired
    private PmsProductCommentFileMapper fileMapper;
    @Autowired
    private PmsProductCommentLabelMapper labelMapper;
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public void ProductComment(CommentRes commentRes) {
            commentMapper.addComment(commentRes);
        CommentServiceImpl bean = applicationContext.getBean(CommentServiceImpl.class);
        bean.addCentre(commentRes);
        bean.addFile(commentRes);
    }
    @Async
    public void addCentre(CommentRes commentRes){
        try {
            if (commentRes.getLabels().length>0 && commentRes.getLabels()!=null){
                centreMapper.addCentre(commentRes.getId(),commentRes.getLabels(),commentRes.getCreateBy());
            }
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @Async
    public void addFile(CommentRes commentRes){
        try {
            if (commentRes.getFiles()!=null){
                fileMapper.addFile(commentRes.getFiles(),commentRes.getId(),commentRes.getCreateBy());
            }
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public CommentReq FindComment(Long productId) {
        try {
            ArrayList<Comments> list = new ArrayList<>();
            Comments comments = new Comments();
            List<ProductComment> productComments = commentMapper.findComments(productId);
            List<Long> ids = productComments.stream()
                    .map(ProductComment::getId)
                    .collect(Collectors.toList());

            Future<List<PmsProductCommentFile>> filesFuture = findFiles(ids);
            if (!filesFuture.isDone()) {
                log.error("程序未执行完成请等待");
            }
            List<PmsProductCommentFile> findFiles = filesFuture.get();
            comments.setFiles(findFiles);
            Future<List<PmsProductCommentLabel>> labelFuture = findCommentLabel(ids);
            if (!labelFuture.isDone()) {
                log.error("程序未执行完成请等待");
            }
            List<PmsProductCommentLabel> findLabel = labelFuture.get();
            comments.setLabel(findLabel);
            for (ProductComment productComment : productComments) {
                comments.setContent(productComment.getContent());
                comments.setTimestamp(productComment.getCrateTime());
                comments.setName(productComment.getCreateBy());
                JSONArray array = new JSONArray(productComment.getSpData());
                StringBuilder spData = new StringBuilder();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    String value = jsonObject.getString("value");
                    spData.append(value).append(" ");
                }
                comments.setSpData(spData.toString());
                list.add(comments);
            }

            Double countFavorable = (double) commentMapper.Counthao(productId);
            int countSum = commentMapper.CountSum(productId);

            CommentReq commentReq = new CommentReq();
            commentReq.setComments(list);
            commentReq.setSum(countSum);
            Double favorableRate = ((countFavorable / countSum) * 100);
            commentReq.setFavorableRate(favorableRate);

            return commentReq;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Async
   public Future<List<PmsProductCommentFile>> findFiles(List<Long> ids){
       List<PmsProductCommentFile> commentFile=fileMapper.findCommentFile(ids);
       return new AsyncResult<>(commentFile);
   }
    @Async
   public Future<List<PmsProductCommentLabel>>  findCommentLabel(List<Long> ids){
       List<PmsProductCommentLabelCentre> commentLabels=centreMapper.findCommentLabel(ids);
       List<Integer> labelIds = commentLabels.stream()
               .map(PmsProductCommentLabelCentre::getLabelId)
               .collect(Collectors.toList());
       List<PmsProductCommentLabel> commentLabelList =labelMapper.findCommentLabel(labelIds);
       return new AsyncResult<>(commentLabelList);
   }

}
